package br.com.sispac.model;

import java.util.Collections;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

public class GenericDao<T, K> implements Dao<T, K> {

	private static final long serialVersionUID = 1L;

	private Class<T> classe;
	private EntityManager em;
	
	public void setEm(EntityManager em) {
		this.em = em;
	}

	public GenericDao(Class<T> classe) {
		super();
		this.classe = classe;
	}

	@Override
	public void save(T element) {
		em.getTransaction().begin();
		em.persist(element);
		em.getTransaction().commit();
	}

	@Override
	public void update(T element) {
		em.getTransaction().begin();
		em.merge(element);
		em.getTransaction().commit();
	}

	@Override
	public void delete(T element) {
		em.getTransaction().begin();
		em.remove(element);
		em.getTransaction().commit();
	}

	@Override
	public T findById(K key) {
		em.getTransaction().begin();
		return em.find(classe, key);
	}

	@Override
	public List<T> findAll() {
		em.getTransaction().begin();
		
		String jpql = "SELECT Q FROM " + classe.getSimpleName() + " C"; 
		try {
			TypedQuery<T> query = em.createQuery(jpql, classe);
			return query.getResultList();
		} catch (Exception e) {
			return Collections.emptyList();
		}
	}
}
